#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QSharedMemory>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    m_pCameraThread = new GetCameraFrame_Thread(this);

    connect(&m_VideoTimer,&QTimer::timeout,[=]() {
        QImage img;
        if(GetVideoFrame(img)){
            ui->widget->setImage(img);
        }
    });

    m_VideoTimer.start(70);
}

Dialog::~Dialog()
{
    m_pCameraThread->m_bExit = true;
    m_pCameraThread->quit();
    m_pCameraThread->wait(500);
    m_pCameraThread->terminate();
    delete ui;
}

static QSharedMemory* g_pShareVid = nullptr;

bool Dialog::GetVideoFrame(QImage &Img)
{
    bool bResult = false;
    if (nullptr == g_pShareVid) {
        g_pShareVid = new QSharedMemory("Robot_Camera_Live");
    }
    if (!g_pShareVid->isAttached()) {
        g_pShareVid->attach();
    }
    if (g_pShareVid->isAttached()) {
        int nWidth = 0; int nHeight = 0;
        static uint8_t *buffer = new uint8_t[2048*1536*3+5];
        g_pShareVid->lock();
        int *pMemData = nullptr;
        pMemData = (int*)g_pShareVid->data();
        if(nullptr != pMemData) {
            nWidth = pMemData[0];
            nHeight = pMemData[1];
            memcpy((void*)buffer, (void*)(pMemData+2), nWidth*nHeight*3);
        }
        g_pShareVid->unlock();
        if(nWidth > 0 && nHeight > 0) {
            QImage tmpImg(buffer,nWidth,nHeight,QImage::Format_RGB888);
            Img = tmpImg.scaled(640, 480);
            bResult = true;
        }else{
            bResult = false;
            qDebug() << "GetVideoFrame g_pShareVid error";
        }
    }
    return bResult;
}


